import { nanoid } from 'nanoid';
import { currentShape, copySet, selectSet } from '../data/shapes';
import { currentStage, allowPaste } from '../data/stage';
import type { IShapeProps } from '../types/IShape';
import { unredo } from './undo.redo';

/**
 * 注释: 根据ID删除一个图形
 *
 * */
export const deleteShapeById = (id: string) => {
  currentStage.value.components = currentStage.value.components.filter(item => {
    return item.id !== id;
  });
  currentShape.value.id = '';
};

export const addShape = (item: IShapeProps) => {
  currentStage.value.components.unshift(item);
};

/* 更新组件的状态 */
export const updateShape = (item: IShapeProps) => {
  currentStage.value.components = currentStage.value.components.filter(e => {
    if (e.id === item.id) {
      e = item;
    }
    return e;
  });
};
/**
 * 注释:根据ID寻找图形的属性
 *
 * */
export const findShapeById = (id: string): any => {
  return currentStage.value.components.find(e => {
    if (e.id === id) {
      return e;
    }
    return null;
  });
};
/* 隐藏图形 */
export const toggleById = (id: string) => {
  const shape = findShapeById(id);
  if (!shape) return;
  shape.show = !shape.show;
};

/* 复制一个组件 */
export const copyShape = () => {
  if (!currentShape.value.id) return;
  copySet.value = currentShape.value;
};
/* 获取最大的层级 */
export const getMaxIndex = () => {
  return currentStage.value.components.length;
};
/* 粘贴一个图形 */
export const pasteShape = () => {
  if (!allowPaste.value) return;
  if (!copySet.value) return;
  const newShape = JSON.parse(JSON.stringify(copySet.value));
  newShape.id = nanoid();
  // eslint-disable-next-line no-use-before-define
  newShape.z = getMaxIndex() + 1;
  newShape.x += 1;
  newShape.y += 1;
  addShape(newShape);
};

/**
 * 注释: 根据层级查找对象
 *
 * */
const findByZ = (z: number) => {
  return currentStage.value.components.find(item => {
    if (item.z === z) {
      return true;
    }
    return null;
  });
};

/**
 * 注释: 重置列表
 *
 * */
export const resetShapeList = () => {
  currentStage.value.components = currentStage.value.components.sort(
    (a: IShapeProps, b: IShapeProps) => {
      return b.z - a.z;
    },
  );
  unredo.save();
};
const exchangeZ = (z1: number, z2: number) => {
  const current = findByZ(z1);
  const last = findByZ(z2);
  if (!current || !last) return;
  [current.z, last.z] = [last.z, current.z];
  selectSet.value.clear();
  resetShapeList();
};

/* 向上移动一层 */
export const moveUp = (z: number) => {
  exchangeZ(z, z + 1);
};
/* 向下移动一层 */
export const moveDown = (z: number) => {
  exchangeZ(z, z - 1);
};
/* 置顶 */
export const moveToTop = (z: number) => {
  const mz = getMaxIndex();
  exchangeZ(z, mz);
};
/* 置顶 */
export const moveToBottom = (z: number) => {
  exchangeZ(z, 1);
};

/* 删除所有图形 */
export const deleteAllShapes = () => {
  currentStage.value.components = [];
  unredo.save();
};
